package com.beike.controller;

import com.beike.common.PageResult;
import com.beike.common.Result;
import com.beike.dto.LoginDTO;
import com.beike.entity.User;
import com.beike.entity.UserRole;
import com.beike.service.UserService;
import com.beike.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CrossOrigin  // 允许跨域请求
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    @Autowired
    public UserController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/login")
    public Result<LoginDTO> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 打印接收到的登录请求信息，方便调试
            System.out.println("Login request - username: " + loginRequest.getUsername() 
                + ", role: " + loginRequest.getRole());
            
            UserRole userRole = UserRole.fromValue(loginRequest.getRole());
            if (userRole == null) {
                return Result.error("无效的角色类型：" + loginRequest.getRole());
            }

            UserRole validatedRole = userService.login(
                loginRequest.getUsername(), 
                loginRequest.getPassword(), 
                userRole
            );

            if (validatedRole != null) {
                LoginDTO loginDTO = new LoginDTO();
                loginDTO.setUsername(loginRequest.getUsername());
                loginDTO.setRole(validatedRole);
                // 生成JWT token
                String token = jwtUtil.generateToken(loginRequest.getUsername(), validatedRole.getValue());
                loginDTO.setToken(token);
                return Result.success(loginDTO);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (IllegalArgumentException e) {
            return Result.error("角色验证失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息到控制台
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    // 创建用户
    @PostMapping
    public Result<User> createUser(@RequestBody User user) {
        try {
            User createdUser = userService.createUser(user);
            return Result.success(createdUser);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 更新用户
    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        try {
            User updatedUser = userService.updateUser(id, user);
            return Result.success(updatedUser);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return Result.success(null);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    public Result<PageResult<User>> getUserList(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) UserRole role,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        PageResult<User> pageResult = userService.getUsersByPage(
                username, name, role, status, current, pageSize
        );
        return Result.success(pageResult);
    }

    // 获取单个用户
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            return Result.success(user);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 重置密码
    @PostMapping("/{id}/reset-password")
    public Result<Void> resetPassword(@PathVariable Long id) {
        try {
            userService.resetPassword(id);
            return Result.success(null);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 更新用户状态
    @PutMapping("/{id}/status")
    public Result<Void> updateStatus(
            @PathVariable Long id,
            @RequestParam String status) {
        try {
            userService.updateStatus(id, status);
            return Result.success(null);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
}

// 添加请求体类
class LoginRequest {
    private String username;
    private String password;
    private String role;

    // Getters and Setters
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}
